//
//  ViewController.m
//  NSStreamSocket
//
//  Created by MyMac on 15/11/4.
//  Copyright © 2015年 tongfang. All rights reserved.
//

#import "ViewController.h"

@interface ViewController ()<NSStreamDelegate>{
    NSInputStream*_inputStream;
    NSOutputStream*_outputStream;


}
@property (weak, nonatomic) IBOutlet UILabel *content;
@property(nonatomic,strong)NSInputStream*input;
@property(nonatomic,strong)NSOutputStream*output;
@property (weak, nonatomic) IBOutlet UILabel *state;
@property (weak, nonatomic) IBOutlet UIImageView *imageView;
@property(nonatomic,strong)NSMutableData*data;
@property(nonatomic,strong)NSData*contentData;
@end

@implementation ViewController
- (IBAction)send:(id)sender {
    uint8_t buffer[]="你好";
    
        [self.output write:buffer maxLength:sizeof(buffer)];
    
}
- (IBAction)connection:(id)sender {
    
    NSInputStream*tempInput=nil;
    NSOutputStream*tempOutput=nil;
    
    //[self getStreamsToHostNamed:@"192.168.1.206" port:8000 inputStream:&tempInput outputStream:&tempOutput];

    
    
    
    
    
    [NSStream getStreamsToHostWithName:@"192.168.1.206" port:8000 inputStream:&tempInput outputStream:&tempOutput];
    
    self.input=tempInput;
    self.output=tempOutput;
    self.input.delegate=self;
    self.output.delegate=self;
    
    
    
//    [self.input setProperty:NSStreamSocketSecurityLevelSSLv3 forKey:NSStreamSocketSecurityLevelKey];
//    [self.output setProperty:NSStreamSocketSecurityLevelSSLv3 forKey:NSStreamSocketSecurityLevelKey];
    //不需要SSL的话，下面这行可以去掉。
   // CFWriteStreamSetProperty((CFWriteStreamRef)tempOutput, kCFStreamPropertySSLSettings, (__bridge CFTypeRef)([NSMutableDictionary dictionaryWithObjectsAndKeys:(id)kCFBooleanFalse,kCFStreamSSLValidatesCertificateChain,kCFBooleanFalse,kCFStreamSSLIsServer,nil]));

    [self.input scheduleInRunLoop:[NSRunLoop mainRunLoop] forMode:NSRunLoopCommonModes];
    [self.input open];
    [self.output scheduleInRunLoop:[NSRunLoop mainRunLoop] forMode:NSRunLoopCommonModes];
   
    [self.output    open];
    
    
    
}
-(void)getStreamsToHostNamed:(NSString *)hostName port:(NSInteger)port inputStream:(NSInputStream **)inputStream outputStream:(NSOutputStream **)outputStream
{
    CFHostRef           host;
    CFReadStreamRef     readStream;
    CFWriteStreamRef    writeStream;
    
    readStream = NULL;
    writeStream = NULL;
    
    host = CFHostCreateWithName(NULL, (__bridge CFStringRef) hostName);
    if (host != NULL) {
        (void) CFStreamCreatePairWithSocketToCFHost(NULL, host, (SInt32)port, &readStream, &writeStream);
        CFRelease(host);
    }
    
    if (inputStream == NULL) {
        if (readStream != NULL) {
            CFRelease(readStream);
        }
    } else {
        *inputStream = (__bridge NSInputStream *) readStream;
    }
    //0x00007fff5a2b43a0
    if (outputStream == NULL) {
        if (writeStream != NULL) {
            CFRelease(writeStream);
        }
    } else {
        *outputStream =(__bridge NSOutputStream *) writeStream;
    }
}
static NSInteger i=-1;
-(void)stream:(NSStream *)aStream handleEvent:(NSStreamEvent)eventCode{
    NSLog(@"%@",aStream);
    switch (eventCode) {
        case NSStreamEventNone:
            NSLog(@"没有事件");
            break;
            case NSStreamEventOpenCompleted:
            NSLog(@"完成链接");
            break;
        case NSStreamEventHasBytesAvailable:{
            if ([aStream isEqual:self.input]) {
                uint8_t buffer[1024];
                while ([self.input hasBytesAvailable]) {
                    NSUInteger copunt=  [(NSInputStream*)aStream read:buffer maxLength:1024];
                    if (copunt!=0) {
                        [self.data appendBytes:(const void *)buffer length:copunt];

                }

                }

            }
            
        
        }
            break;
        case NSStreamEventEndEncountered:{
           if ([aStream isEqual:self.input]) {
//               UIImage*image=[UIImage imageWithData:self.data];
//               self.imageView.image=image;
                NSString*str=[[NSString alloc]initWithData:self.data encoding:NSUTF8StringEncoding];
                self.content.text=str;
           }else if([aStream isEqual:self.output]){
               [self.output close];
           
           }
        
        }
        case NSStreamEventHasSpaceAvailable:{
            if ([aStream isEqual:self.output]) {
                self.state.text=@"可写入";
                NSInteger len=0;
                if (_contentData.length-(i+1)>=1024) {
                    len=1024;
                }else{
                    len=_contentData.length-(i+1);
                }
                //分段写入
                NSData*current=[_contentData subdataWithRange:NSMakeRange(i+1, len)];
                
                
                if (i+1<_contentData.length) {
                    NSUInteger count=[self.output write:( const uint8_t*)[current bytes] maxLength:len];
                    NSLog(@"%ld",count);

                }

                i+=len;

            }
        
        }
            break;
            case NSStreamEventErrorOccurred:
            NSLog(@"'错误%ld",[[aStream streamError] code]);
        default:
            break;
    }
  





}
- (void)viewDidLoad {
    [super viewDidLoad];
    self.data=[[NSMutableData alloc]init];
    NSString*s=@"你好";
  self.contentData=[s dataUsingEncoding:NSUTF8StringEncoding];
       // self.contentData=[NSData dataWithContentsOfFile:[[NSBundle mainBundle]pathForResource:@"屏幕快照 2015-11-02 下午5.09.05.png" ofType:nil ]];
    
    
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

@end
